﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation.Runspaces;
using System.Management.Automation;
using System.Collections.ObjectModel;
using System.Reflection;

namespace PoSHEditor
{
    public class ScriptEngine
    {
        private Runspace _theRunspace;
        private List<string> _commands = new List<string>();
        private bool _addOutString = false;

        public Runspace TheRunspace
        {
            get
            {
                if (_theRunspace == null)
                {
                    _theRunspace = RunspaceFactory.CreateRunspace();
                    _theRunspace.Open();
                }
                return _theRunspace;
            }
        }

        public Collection<PSObject> InvokeScript(string cmd)
        {
            Pipeline pipeline = TheRunspace.CreatePipeline(cmd);

            if (_commands.Count > 0)
                foreach (string command in _commands)
                    pipeline.Commands.Add(command);

            if (_addOutString)
                pipeline.Commands.Add("Out-String");

            return pipeline.Invoke();
        }
        
        public InvokeScriptResults InvokeScriptWithResults(string cmd)
        {
            InvokeScriptResults results = new InvokeScriptResults();

            try { results.PSObjects = InvokeScript(cmd); }
            catch (Exception ex) { results.Exception = ex; }

            return results;
        }

        public void SetVariable(string name, object value)
        {
            TheRunspace.SessionStateProxy.SetVariable(name, value);
        } 

        public void AddCommand(string command)
        {
            _commands.Add(command);
        }

        public void AddOutString(bool flag)
        {
            _addOutString = flag;
        }
    }

    public class InvokeScriptResults
    {
        private Collection<PSObject> _PSObjects ;
        private Exception _exception;

        public Exception Exception
        {
            get { return _exception; }
            set { _exception = value; }
        }
	
        public Collection<PSObject> PSObjects
        {
            get { return _PSObjects ; }
            set { _PSObjects  = value; }
        }

        
        //public Exception Exception { get; set; }
    }
}